package com.greate.community.event;

import com.alibaba.fastjson.JSONObject;
import com.greate.community.entity.Event;
import com.greate.community.entity.Message;
import com.greate.community.service.DiscussPostService;
import com.greate.community.service.ElasticsearchService;
import com.greate.community.service.MessageService;
import com.greate.community.util.CommunityConstant;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "${mq.system.like.totic}"
        ,consumerGroup = "${mq.like.consumer.group.name}")
public class EventLikeListener implements RocketMQListener<MessageExt>, CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(EventLikeListener.class);

    @Autowired
    private MessageService messageService;


    /**
     * 点赞事件
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        //事件
        Event event = null;

        if (messageExt == null || messageExt.getBody() == null) {
            logger.error("消息的内容为空");
            return;
        }
        try {
            //解析内容
            String body = new String(messageExt.getBody(), "UTF-8");
            event = JSONObject.parseObject(body, Event.class);

            if (event == null) {
                logger.error("消息格式错误");
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        // 发送系统通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        if (!event.getData().isEmpty()) { // 存储 Event 中的 Data
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(content));
        logger.info("消费成功");
        messageService.addMessage(message);
    }
}
